<template>
  <view>
    <view>
      <button :disabled="status!='init'" type="primary" @click="startGame">开始游戏</button>
    </view>
    <view v-if="gameinfo.answer && gameinfo.answer.length>0">

      <view>第{{gameinfo.level}}关</view>

      <view class="buttons">
        <button v-for="d in gameinfo.idioms" type="primary">{{d}}</button>
      </view>

      <view class="buttons">
        <button v-for="d in gameinfo.answer" @click="answer(d)" type="warn">{{d}}</button>
      </view>

      <view class="">
        <text>还剩{{ countdown }}秒</text>
      </view>

    </view>

  </view>
</template>

<script setup>
  import {
    ref,
    onMounted,
    onUnmounted
  } from 'vue'

  import {
    api
  } from '@/js/api.js'

  const limit = ref(30)
  const countdown = ref(30)
  const gameinfo = ref({})
  const status = ref('init')
  let timer = -1

  const answer = (info) => {
    api.post('/autodata/idiom/game', {
      answer: info
    }, (data) => {
      if (data.success) {
        startGame()
      } else {
        stopGame('回答错误，游戏结束！')
      }
    })
  }


  const startGame = () => {
    clearInterval(timer)
    status.value = 'playing'
    api.get('/autodata/idiom/game', {}, (data) => {
      if (!data.success) {
        uni.showModal({
          content: data.message,
          title: '错误',
        })
        return
      }
      // 游戏信息处理
      gameinfo.value = data.data
      // 将成语拆分成单个字
      let idioms = gameinfo.value.idiom.split('')
      // 添加提示词
      idioms.splice(gameinfo.value.index, 0, '__');
      gameinfo.value.idioms = idioms
      // 答案数组
      gameinfo.value.answer = gameinfo.value.results.split('')
      // 计时信息
      countdown.value = Math.floor(
        (gameinfo.value.timeout - gameinfo.value.now) / 1000
      )
      // 开始倒计时
      timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          stopGame('游戏超时！')
        }
      }, 1000)

    })
  }
  const stopGame = (reason) => {
    clearInterval(timer)
    status.value = 'init'
    gameinfo.value = {}
    uni.showToast({
      title: reason
    })
  }
</script>

<style scoped lang="scss">
  .buttons {
    display: flex;
    justify-content: center;

    button {
      margin: 0.2rem;
    }
  }
</style>